﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;

namespace MSBIHelper.Helper
{
    /// <summary>
    /// Thanks Gwk for these code
    /// </summary>
    class FormFactory
    {
        private FormFactory()
        {
        }

        private static Dictionary<string, Form> formCache = new Dictionary<string, Form>();

        public  static Form Create(Type type)
        {
            string key = type.FullName;
            return Create(type, null, key);
        }

        public  static Form Create(string filePath, string key)
        {
            return Create(null, filePath, key);
        }

        private static Form Create(Type type, string filePath, string key)
        {
            if (string.IsNullOrEmpty(key) && type != null)
                key = type.FullName;

            try
            {
                if (!formCache.ContainsKey(key))
                {
                    formCache.Add(key, CreateForm(type, filePath, key));
                }
                else
                {
                    if (formCache[key].IsDisposed)
                    {
                        formCache[key] = CreateForm(type, filePath, key);
                    }
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }

            return formCache[key];
        }

        private static Form CreateForm(Type type, string filePath, string key)
        {
            Form form = null;
            if (type != null)
            {
                form = (Form)type.Assembly.CreateInstance(type.FullName);
            }
            else if (!string.IsNullOrEmpty(filePath))
            {
                form = (Form)Assembly.LoadFrom(filePath).CreateInstance(key);
            }
            else
            {
                form = (Form)typeof(FormFactory).Assembly.CreateInstance(key);
            }
            if (form == null)
                throw new Exception(string.Format("Cant Create object:{0}", type.FullName));

            return form;
        }
 

    }
}
